﻿Imports NHibernate.Criterion

Public Class UserRepository
    Private myUsersList As IList(Of UserObj)
    Private myUserPicksList As IList(Of UserPicksObj)

    Public Property UsersList() As IList(Of UserObj)
        Get
            Return myUsersList
        End Get
        Set(ByVal value As IList(Of UserObj))
            myUsersList = value
        End Set
    End Property

    Public Property UserPicksList() As IList(Of UserPicksObj)
        Get
            Return myUserPicksList
        End Get
        Set(ByVal value As IList(Of UserPicksObj))
            myUserPicksList = value
        End Set
    End Property

    Public Sub UpdateUserDisplayName(username As String, displayName As String)
        Using mySession = Persister.OpenSession()
            Dim crit = mySession.CreateCriteria(GetType(UserObj))
            crit.Add(Restrictions.Eq("UserName", username))
            Dim users = crit.List(Of UserObj)()

            If users.Count = 1 Then
                Dim user = users(0)
                user.DisplayName = displayName

                Using myTrans = mySession.Transaction
                    myTrans.Begin()
                    mySession.SaveOrUpdate(user)
                    myTrans.Commit()
                End Using
            End If
        End Using
    End Sub

    Public Function FindAllUsers() As IList(Of UserObj)
        Using mySession = Persister.OpenSession()
            Dim crit = mySession.CreateCriteria(GetType(UserObj))
            crit.AddOrder(Order.Desc("StillAlive"))
            crit.AddOrder(Order.Asc("DisplayName"))
            Return crit.List(Of UserObj)()
        End Using
    End Function

    Public Function GetListOfUserPicks(Optional ByVal curRound As Integer = -1) As List(Of UserPicksObj)
        Dim myList As New List(Of UserPicksObj)
        Dim picksList As New PickRepository()
        Dim usersList As New UserRepository()
        Dim users = usersList.FindAllUsers()
        For Each usr In users
            Dim newObj As New UserPicksObj()
            newObj.User = usr
            If curRound = -1 Then
                newObj.Picks = picksList.FindAllPicksPerUser(usr.UserName)
            Else
                newObj.Picks = picksList.FindAllPicksPerUserUpToSpecificRound(usr.UserName, curRound)
            End If
            myList.Add(newObj)
        Next
        Return myList
    End Function

End Class
